package com.hmsm.server.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

/**
 * 
 *  @描述:读取*.properties文件
 *  @作者:yaosq
 *  @创建日期:2014-4-1 下午03:39:09  
 *
 */
public class ProperConfig {
	private static ProperConfig instance = null;

	private static final String CONFIG_FILE_NAME = "/application.properties";

	private static Map<String, String> applicationProper = null;

	private ProperConfig() {
	}

	/**
	 * 
	 *  @描述:初始化数据
	 *  @方法名称:getInstance
	 *  @作者:yaosq
	 *  @创建日期:2014-4-1 下午03:39:21 
	 *  @param cfgFilename
	 *  @return
	 *
	 */
	static synchronized public Properties getInstance(String cfgFilename) {
		if (instance == null) {
			instance = new ProperConfig();
		}
		Properties sysProp = instance.parse(cfgFilename);
		return sysProp;
	}

	/**
	 * 
	 *  @描述:描述:设置applicationProper
	 *  @方法名称:setApplicationProper
	 *  @作者:yaosq
	 *  @创建日期:2014-4-1 下午03:39:33 
	 *
	 */
	static synchronized public void setApplicationProper() {
		if (applicationProper == null) {
			applicationProper = new HashMap<String, String>();
			Properties proper = ProperConfig.getInstance(CONFIG_FILE_NAME);

			Iterator<Entry<Object, Object>> properAll = proper.entrySet().iterator();
			while (properAll.hasNext()) {
				Entry<Object, Object> entry = properAll.next();
				applicationProper.put(entry.getKey().toString(), entry.getValue().toString());
			}
		}
	}

	/**
	 * 
	 *  @描述:解析资源文件
	 *  @方法名称:parse
	 *  @作者:yaosq
	 *  @创建日期:2014-4-1 下午03:39:52 
	 *  @param cfgFileName
	 *  @return
	 *
	 */
	private Properties parse(String cfgFileName) {
		Log.log(this, "解析资源文件：" + cfgFileName);
		Properties props = new Properties();
		try {
			InputStream is = this.getClass().getResourceAsStream(cfgFileName);
			if (is==null){
				Log.logError(this, "资源文件不存在：");
			}else{
				try {
					props.load(is);
				} catch (IOException e) {
					e.printStackTrace();
					Log.logError(this, "解析资源文件错误：" + e.toString());
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			Log.logError(this, "解析资源文件错误：" + ex.toString());
		}
		return props;
	}

	/**
	 * 
	 *  @描述:获取应用程序配置文件信息
	 *  @方法名称:getApplicationProper
	 *  @作者:yaosq
	 *  @创建日期:2014-4-1 下午03:40:05 
	 *  @return
	 *
	 */
	public static Map<String, String> getApplicationProper() {
		setApplicationProper();
		return applicationProper;
	}
}
